﻿
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using ProductionLine.Modules.ShareLib.Helpers;
using ProductionLine.Modules.ShareLib.Models;
using System;
using System.Linq;
using System.Threading.Tasks;

namespace ProductionLine.Modules.Device.ViewModels;

public partial class DeviceViewModel : ObservableObject {
    #region 属性

    [ObservableProperty]
    private  GlobalConfig _globalConfigProp;

    [ObservableProperty]
    private  UserSession _userSession;

    [ObservableProperty]
    private ScadaReadData _scadaReadDataProp;

    [ObservableProperty]
    private PlcParam _plcParam;

    #endregion


    public DeviceViewModel(GlobalConfig globalConfigProp, UserSession userSession, PlcParam plcParam) {
        _plcParam = plcParam;

        _globalConfigProp = globalConfigProp;

        _scadaReadDataProp = globalConfigProp.ScadaReadDataProp;

        _userSession = userSession;



    }

    /// <summary>
    /// 开关按钮
    /// </summary>
    /// <param name="paramName">那个开关按钮</param>
    [RelayCommand]
    async Task WriteDeviceControl(string paramName) {

        bool isSuccess = GeneralControlOfTheProductionLine(paramName);

        //总启动
        if (paramName == "TotalStart" && isSuccess) {

            //plc未连接,则连接plc
            if (!GlobalConfigProp.PlcConnected) {
             
                //_userSession.ShowMessage("PLC未连接或连接异常");
             
                await GlobalConfigProp.InitPlcServer();

                if (GlobalConfigProp.PlcConnected) {
                
                    // _userSession.ShowMessage("PLC连接成功");
                } else {
                 
                    // _userSession.ShowMessage("PLC连接成功");
                    return;
                }


            }

            //plc已连接
            if (GlobalConfigProp.PlcConnected) {
                //自动采集已开启
                if (PlcParam.AutoCollect) {
                 
                    //_userSession.ShowMessage("AutoCollect自动采集已开启");
                    GlobalConfigProp.StartCollectionIndex();//不能await,否则五个按钮都按不了
                }
                if (!PlcParam.AutoCollect) {//自动采集未开启,尝试开启
               
                    //_userSession.ShowMessage("AutoCollect自动采集未开启,尝试开启");
                    //Task.Run(async () => {
                    //    PlcParam.AutoCollect = true;//自动采集开启
                    //    await GlobalConfigProp.StartCollectionAsync();
                    //    PlcParam.AutoCollect = false;//自动采集关闭
                    //});
                    PlcParam.AutoCollect = true;//自动采集开启
                    GlobalConfigProp.StartCollectionIndex();//不能await,否则五个按钮都按不了

                }
            }

        }

        //总停止
        if (paramName == "TotalStop" && isSuccess) {
            PlcParam.AutoCollect = false;
            GlobalConfigProp.StopCollection();


            //_userSession.ShowMessage("总停止-停止自动采集");
            GlobalConfigProp.PlcConnected = false;

            //_userSession.ShowMessage("PLC已断开");
        }
        //机械复位
        if (paramName == "MechanicalReset" && isSuccess) {//机械复位

        }
        ////plc已连接
        ////读取该参数的地址,使用空条件运算符
        //var readAddress = GlobalConfigProp.ReadEntities.FirstOrDefault(x => x.En == paramName)?.Address;
        ////判断地址是否为空
        //if (string.IsNullOrEmpty(readAddress)) {
        //    LogContent += "找不到对应的读取地址" + Environment.NewLine;
        //    _userSession.ShowMessage("找不到对应的读取地址");
        //    return;
        //}
        ////若地址不为空
        //// 写入 PLC 数据,将该地址置true,返回result
        //var result = GlobalConfigProp.Plc.Write(readAddress, true);
        ////是否修改成功,成功则写入日志
        //if (result.IsSuccess) {
        //    // 记录日志
        //    LogContent += $"写入{paramName} 地址{readAddress} 写入值:true{Environment.NewLine}";
        //}
    }

    /// <summary>
    /// 产线总控制写入true
    /// </summary>
    /// <param name="paramName"></param>
    private bool GeneralControlOfTheProductionLine(string paramName) {

        var ReadAddress = GlobalConfigProp.ReadEntities.FirstOrDefault(x => x.En == paramName)?.Address;

        //判断地址是否为空
        if (string.IsNullOrEmpty(ReadAddress)) {
      
            //_userSession.ShowMessage("找不到对应的读取地址");
            return false;
        }
        //若地址不为空
        // 写入 PLC 数据,将该地址置true,返回result
        var resultStart = GlobalConfigProp.Plc.Write(ReadAddress, true);
        //是否修改成功,成功则写入日志
        if (resultStart.IsSuccess) {
            // 记录日志
       
            return true;
        } else {
            // 记录日志
     
            return false;
        }

    }



    /// <summary>
    /// plc是否开启
    /// </summary>
    /// <returns></returns>
    private bool CanToggleCollection() {
        return GlobalConfigProp.PlcConnected;
    }

    /// <summary>
    /// CanToggleCollection:用于判断是否执行
    /// </summary>
    /// <param name="paramName"></param>
    [RelayCommand(CanExecute = nameof(CanToggleCollection))]
    void ToggleCollection(string paramName) {
        //plc未开启
        if (!GlobalConfigProp.PlcConnected) {
            //LogContent += "PLC未连接或连接异常" + Environment.NewLine;
            //_userSession.ShowMessage("PLC未连接或连接异常");

            return;
        }
        //plc已开启
        var readAddress = GlobalConfigProp.ReadEntities.FirstOrDefault(x => x.En == paramName);

        if (readAddress == null) {
            //_userSession.ShowMessage("找不到对应的读取地址");
            return;
        }

        // 写入 PLC 数据
        var value = (bool)ScadaReadDataProp.GetType().GetProperty(readAddress.En)?.GetValue(ScadaReadDataProp);
        var result = GlobalConfigProp.Plc.Write(readAddress.Address, !value);

        if (result.IsSuccess) {
            // 记录日志
            //Utils.LogContent += $"写入{paramName} 地址{readAddress.Address} 写入值:{!value}{Environment.NewLine}";
        }
    }
}